<style>
.popoverBackB {
  /* #303133是el-tooltip的背景色 */
  background: #303133 !important;
}

.popoverBackB .popper__arrow::after {
  /* 注意：placement位置不同，下面的属性不同 */
  border-bottom-color: #303133 !important;
}

.el-row {
  display: flex;
  flex-wrap: wrap;
}

.describe {
  background-color: gray;
}
</style>
<template>
  <div>
    <el-table :data="albumTable" :header-cell-style="{'text-align':'center'}" ref="table"
              :cell-style="{'text-align':'center'}" @cell-click="tableRowClick"
              :row-key="getRowKeys" :expand-row-keys="expands" @expand-change="expandColumn">
      <el-table-column type="expand">
        <div slot-scope="scope" style="margin-left: 75px">
          <div style="margin-bottom: 10px">
            <el-pagination @size-change="(pageSize)=>handlePictureSizeChange(pageSize,scope.row.id)"
                           @current-change="(page)=>handlePictureCurrentChange(page,scope.row.id)"
                           :current-page="scope.row.page" :page-sizes="[6,12,18,24,30]" :page-size="scope.row.pageSize"
                           layout="total, sizes, prev, pager, next, jumper" :total="scope.row.total"
                           style="display: inline-block"/>
            <el-upload style="display: inline-block"
                       action="http://localhost:9999/zx-resource/resources/upload/image/product"
                       :on-success="(response)=>pictureSuccess(response,scope.row.id)" :show-file-list="false">
              <el-button style="vertical-align: top;margin-left: 20px" type="primary" size="mini">新增图片</el-button>
            </el-upload>
          </div>
          <el-row :gutter="20">
            <el-col :span="4" v-for="pic in scope.row.picture">
              <el-popover popper-class="popoverBackB">
                <div style="border-radius: 10px;overflow: hidden;text-align: center">
                  <div style="margin-bottom: 10px">
                    <span style="color: white">轮播图：</span>
                    <el-switch v-model="pic.slideshow" :active-value="1" :inactive-value="2"
                               @change="slideshowChange(pic.id,pic.slideshow)"/>
                  </div>
                  <el-popover placement="left" popper-class="describe" width="200"
                              @hide="updateDescribe(pic.id,pic.description)">
                    <div>
                      <p style="color: white">图片描述</p>
                      <el-input resize="none" type="textarea" v-model="pic.description"/>
                    </div>
                    <el-button slot="reference" type="success" size="mini">描述
                    </el-button>
                  </el-popover>
                  <el-button style="margin-left: 10px" type="danger" size="mini"
                             @click="deletePicture(pic.id,scope.row.id);">删除
                  </el-button>
                </div>
                <div slot="reference">
                  <el-tooltip placement="top" :disabled="pic.description === null">
                    <div slot="content">
                      <p style="text-align: center;font-size: 15px">{{ pic.description }}</p>
                    </div>
                    <div style="position: relative;">
                      <div style="position: absolute;top:5px;right:5px;z-index: 10;font-size: 20px">
                        <i v-if="pic.slideshow===1" style="color: lightgreen;" class="el-icon-success"/>
                        <i v-else style="color: darkred" class="el-icon-error"/>
                      </div>
                      <el-image style="margin: 0 auto;background-color: #8c939d" :src="pic.url" fit="cover"/>
                    </div>
                  </el-tooltip>
                </div>
              </el-popover>
            </el-col>
          </el-row>
        </div>
      </el-table-column>
      <el-table-column prop="id" label="id" width="100"/>
      <el-table-column prop="name" label="相册名称" width="150"/>
      <el-table-column prop="description" label="相册描述" width="200"/>
      <el-table-column prop="sort" label="序号" width="100"/>
      <el-table-column prop="created" label="创建时间" width="100"/>
      <el-table-column prop="updated" label="更新时间" width="100"/>
      <el-table-column label="操作" width="250">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-search" @click.stop="dataDrawerOpen(scope.row)">数据修改</el-button>
          <el-popover width="250" placement="right" :ref="'deleteBy'+scope.row.id">
            <p style="text-align: center">确认删除：{{ scope.row.name }}？</p>
            <p style="text-align: center">(将滑动条移至右侧以解锁“确认”)</p>
            <el-slider style="width: 100px;margin: 0 auto" v-model="deleteLine" @change="deletePopoverMaxLine($event)"
                       :show-tooltip="false"/>
            <div style="text-align: center">
              <el-button :disabled="confirmDelete" type="danger" @click="deletePopoverUpdate(scope.row.id)">确认删除
              </el-button>
            </div>
            <el-button style="margin-left: 10px" slot="reference" type="danger" icon="el-icon-delete"
                       @click.stop="deletePopoverOpen">删除
            </el-button>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination @size-change="handleSizeChange"
                   @current-change="handleCurrentChange"
                   :current-page="page" :page-sizes="[5,10,20,30,40,50]" :page-size="pageSize"
                   layout="total, sizes, prev, pager, next, jumper" :total="total"/>

    <el-drawer :visible.sync="dataDrawer" :title="'正在修改：'+dataEditForm.name" ref="update">
      <el-form :model="dataEditForm" :rules="dataRule" style="max-width: 450px">
        <el-form-item label="相册名称" prop="name" label-width="100px">
          <el-input v-model="dataEditForm.name" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="相册描述" prop="description" label-width="100px">
          <el-input v-model="dataEditForm.description" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="序号" prop="sort" label-width="100px">
          <el-input v-model="dataEditForm.sort" autocomplete="off"/>
        </el-form-item>
        <div style="text-align: center">
          <el-button type="primary" style="margin-right: 150px" @click="dataDrawerUpdate">修改</el-button>
          <el-button type="danger" @click="dataDrawerClose">取消</el-button>
        </div>
      </el-form>
    </el-drawer><!--普通数据修改栏-->
  </div>
</template>

<script>
export default {
  name: "albumList",
  data() {
    return {
      albumTable: [],
      page: parseInt(""),//当前页数
      pageSize: parseInt(""),//每页展示数
      total: parseInt(""),//最大数据量
      totalPage: parseInt(""),//最大页码
      confirmDelete: true,
      deleteLine: 0,
      dataDrawer: false,
      dataEditForm: {
        id: "",
        name: "",
        description: "",
        sort: "",
      },
      dataRule: {
        id: [],
        name: [],
        description: [],
        sort: [],
      },
      expands: [], // 只展开一行放入当前行id
      getRowKeys: (row) => { // 获取当前行id
        return row.id; // 这里看这一行中需要根据哪个属性值是id
      },
    }
  },
  methods: {
    deletePicture(id, albumId) {
      let url = "http://localhost:9999/zx-album/picture/delete"
      let data = this.qs.stringify({"id": id})
      this.axios.create(
          {'headers': {'Authorization': localStorage.getItem('adminJwt')}}
      ).post(url, data).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state === 200) {
          this.loadPicture(albumId)
        } else {
          this.$message({message: jsonResult.message, type: "error"})
        }
      })
    },
    pictureSuccess(response, id) {
      let jsonResult = response.data;
      let url1 = jsonResult.url;
      let url = "http://localhost:9999/zx-album/picture/addNew";
      let data = this.qs.stringify({"albumId": id, "url": url1})
      this.axios.create(
          {'headers': {'Authorization': localStorage.getItem('adminJwt')}}
      ).post(url, data).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state === 200) {
          this.$message({message: "图片已添至相册", type: "success"})
          this.loadPicture(id);
        }
      })
    },
    updateDescribe(id, description) {
      let data = this.qs.stringify({"id": id, "description": description})
      let url = "http://localhost:9999/zx-album/picture/updateDescription"
      this.axios.create(
          {'headers': {'Authorization': localStorage.getItem('adminJwt')}}
      ).post(url, data).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state != 200) {
          this.$message({message: "修改图片描述出现错误", type: "error"})
        }
      })
    },

    //图片方法
    slideshowChange(id, slideshow) {
      let url = "http://localhost:9999/zx-album/picture/slideshowChange"
      let updateData = this.qs.stringify({"id": id, "slideshow": slideshow});
      this.axios.create(
          {'headers': {'Authorization': localStorage.getItem('adminJwt')}}
      ).post(url, updateData).then((response) => {
        let result = response.data;
        if (result.state !== 200) {
          this.$message({message: result.message, type: "error"})
        }
      })
    },
    handlePictureSizeChange(pageSize, id) {
      for (let a = 0; a < this.albumTable.length; a++) {
        if (this.albumTable[a].id === id) {
          this.albumTable[a].pageSize = pageSize;
          this.loadPicture(id)
          break;
        }
      }
    },//切换图册内图片的每页数量
    handlePictureCurrentChange(page, id) {
      for (let a = 0; a < this.albumTable.length; a++) {
        if (this.albumTable[a].id === id) {
          this.albumTable[a].page = page;
          this.loadPicture(id)
          break;
        }
      }
    },//切换图册内图片页数
    //相册方法
    deletePopoverUpdate(id) {
      let url = "http://localhost:9999/zx-album/album/delete";
      let deleteId = this.qs.stringify({"albumId": id});
      this.axios.create(
          {'headers': {'Authorization': localStorage.getItem('adminJwt')}}
      ).post(url, deleteId).then((response) => {
        if (response.data.state === 200) {
          this.$message({message: "删除完毕，正在刷新页面", type: "success"});
          this.loadAlbumTable();
        } else {
          this.$message({message: response.data.message, type: "error"})
        }
      })
      this.$refs[`deleteBy` + id].doClose();
    },//根据id执行删除并关闭对应的popover删除窗口
    deletePopoverOpen() {
      for (let a = 0; a < this.albumTable.length; a++) {
        this.$refs[`deleteBy` + this.albumTable[a].id].doClose();
      }
      this.deleteLine = 0;
      this.confirmDelete = true;
    },//打开Popover组件，delete
    deletePopoverMaxLine(index) {
      if (index !== 100) {
        this.deleteLine = 0;
      }
      this.confirmDelete = index !== 100;
    },//检查删除确认条是否拉到右侧
    dataDrawerOpen(data) {
      this.dataEditForm.id = data.id;
      this.dataEditForm.name = data.name;
      this.dataEditForm.description = data.description;
      this.dataEditForm.sort = data.sort;
      this.dataDrawer = true;
    },//打开数据修改侧边栏
    dataDrawerClose() {
      this.$refs.update.closeDrawer();
    },//关闭修改侧边栏
    dataDrawerUpdate() {
      let url = "http://localhost:9999/zx-album/album/update";
      let updateData = this.qs.stringify(this.dataEditForm)
      this.axios.create(
          {'headers': {'Authorization': localStorage.getItem('adminJwt')}}
      ).post(url, updateData).then((response) => {
        if (response.data.state === 200) {
          this.$message({message: "数据已修改，正在刷新页面", type: "success"});
          this.loadAlbumTable();
        } else {
          this.$message({message: response.data.message, type: "error"})
        }
      })
      this.dataDrawerClose();
    },//确认修改窗口内容并触发closingDrawer
    expandColumn(row, expandedRows) {
      let that = this;
      if (expandedRows.length) {
        that.expands = []
        if (row) {
          that.expands.push(row.id)
          this.loadPicture(row.id)
        }
      } else {
        that.expands = []
      }
    },// 每次只展开一行（来自网络）
    tableRowClick(row, column, event) {
      if (event.cellIndex !== 0) {
        this.$refs.table.toggleRowExpansion(row)
      }
    },//触发每行任意位置打开展开行（来自网络）
    loadPicture(id) {
      for (let a = 0; a < this.albumTable.length; a++) {
        if (this.albumTable[a].id === id) {
          if (isNaN(this.albumTable[a].page)) this.albumTable[a].page = 1;
          if (isNaN(this.albumTable[a].pageSize)) this.albumTable[a].pageSize = 6;
          let url = "http://localhost:9999/zx-album/picture/list?albumId=" + id + "&pageNum=" + this.albumTable[a].page + "&pageSize=" + this.albumTable[a].pageSize;
          this.axios.create(
              {'headers': {'Authorization': localStorage.getItem('adminJwt')}}
          ).get(url).then((response) => {
            if (response.data.state === 200) {
              this.$set(this.albumTable[a], "picture", response.data.data.list);
              this.$set(this.albumTable[a], "page", response.data.data.page);
              this.$set(this.albumTable[a], "pageSize", response.data.data.pageSize);
              this.$set(this.albumTable[a], "total", response.data.data.total);
              this.$set(this.albumTable[a], "totalPage", response.data.data.totalPage);
            } else {
              this.$message({message: response.data.message, type: "error"})
            }
          })
          break;
        }
      }
    },//根据页码和每页数量加载图片数据
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.loadAlbumTable();
    },//切换每页数量
    handleCurrentChange(pageNum) {
      this.page = pageNum;
      this.loadAlbumTable();
    },//切换页码
    loadAlbumTable() {
      if (isNaN(this.page)) this.page = 1;
      if (isNaN(this.pageSize)) this.pageSize = 5;
      let url = "http://localhost:9999/zx-album/album/list?pageNum=" + this.page + "&pageSize=" + this.pageSize;
      this.axios.create(
          {'headers': {'Authorization': localStorage.getItem('adminJwt')}}
      ).get(url).then((response) => {
        if (response.data.state === 200) {
          this.albumTable = response.data.data.list;
          this.page = response.data.data.page;
          this.pageSize = response.data.data.pageSize;
          this.total = response.data.data.total;
          this.totalPage = response.data.data.totalPage;
        } else {
          this.$message({message: response.data.message, type: "error"})
        }
      })
    }//根据页码和每页数量加载相册数据
  },
  mounted() {
    this.loadAlbumTable();
  }

}
</script>

